package com.mustafaiev.tair.cts.facade;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.dozer.Mapper;

import com.mustafaiev.tair.cts.dao.IPayerDAO;
import com.mustafaiev.tair.cts.exeptions.DataNotRemovedException;
import com.mustafaiev.tair.cts.exeptions.DataNotStoredException;
import com.mustafaiev.tair.cts.model.Payer;
import com.mustafaiev.tair.cts.tapestry.dto.PayerDTO;

public class PayerFacade implements IPayerFacade {

    private final IPayerDAO payerDAO;

    private final Mapper mapper;

    private static final Logger LOGGER = Logger
            .getLogger(PayerFacade.class);

    public PayerFacade(final IPayerDAO payerDAO, final Mapper mapper) {
        this.payerDAO = payerDAO;
        this.mapper = mapper;
    }

    public void savePayer(final PayerDTO payerDto) {
        final Payer payer = mapper.map(payerDto, Payer.class);
        try {
            payerDAO.doSave(payer);
        }
        catch (final DataNotStoredException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
    }

    public List<PayerDTO> retrievePayers() {

        final List<Payer> payers = payerDAO.retrievePayers();

        final List<PayerDTO> payersList = new ArrayList<PayerDTO>();
        if (payers != null) {
            for (final Payer payer : payers) {
                final PayerDTO payerDto = mapper.map(payer,
                        PayerDTO.class);
                payersList.add(payerDto);
            }
        }
        return payersList;
    }

    public PayerDTO retrievePayer(final Long payerId) {
        final Payer payer = payerDAO.retrievePayer(payerId);
        final PayerDTO dto = mapper.map(payer, PayerDTO.class);
        return dto;
    }

    public void deletePayers(final List<PayerDTO> payersToDelete)
            throws DataNotRemovedException {
        final List<Payer> payers = convertList(payersToDelete);
        try {
            payerDAO.deleteBatch(payers);
        }
        catch (final DataNotRemovedException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
    }

    private List<Payer> convertList(final List<PayerDTO> list) {
        final List<Payer> payers = new ArrayList<Payer>();
        for (final PayerDTO payerDto : list) {
            final Payer payer = mapper.map(payerDto, Payer.class);
            payers.add(payer);
        }
        return payers;
    }

}
